package com.server.push.mqtt.base;

import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Data
@Accessors(chain = true)
@Slf4j
public class Topic {
    String received;
    String original;
    String subscribe;

    String[] receivedLevels;
    String[] originalLevels;

    String[] subscribeLevels;

    Map<String,Object> receivedMap;


    public Topic(String received, String original){
        this.received = received;
        this.receivedLevels = received.split("/");

        this.original = original;
        this.originalLevels =  original.split("/");

        this.subscribe = original;

        this.receivedMap = new HashMap<>();
        for (int i = 0; i < originalLevels.length; i++) {
            if(originalLevels[i].startsWith("{") && originalLevels[i].endsWith("}")){
                subscribe = subscribe.replace(originalLevels[i],"+");
                String key = originalLevels[i].replace("{", "").replace("}", "");
                this.receivedMap.put(key, receivedLevels[i]);
            }
        }
        this.subscribeLevels = this.subscribe.split("/");

    }

    public static String getSubscribe(String originalTopic){
        String[] originalTopicLevels =  originalTopic.split("/");
        String subscribeTopic = originalTopic;
        for (String originalTopicLevel : originalTopicLevels) {
            if (originalTopicLevel.startsWith("{") && originalTopicLevel.endsWith("}")) {
                subscribeTopic = subscribeTopic.replace(originalTopicLevel, "+");
            }
        }
        return subscribeTopic;
    }

    public static String setTopic(String topic,Map<String,String> map) {
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            topic = topic.replace("{"+key+"}",value);
        }
        return topic;
    }

    public static String setTopic(String topic,String key, String val) {
        topic = topic.replace("{"+key+"}",val);
        return topic;
    }



}
